<script lang="ts" setup>
import { ref, watch, useTemplateRef, onMounted } from 'vue';
import { useElementVisibility } from '@vueuse/core';

const { finished } = defineProps({
  finished: {
    type: Boolean,
    default: false,
  },
});

const loading = defineModel<boolean>('loading');
const emit = defineEmits(['load']);

const targetRef = useTemplateRef('target');
const targetIsVisible = useElementVisibility(targetRef);
const isInit = ref(true);

const unwatch = watch(
  loading,
  (newValue, oldValue) => {
    if (oldValue === true && newValue === false) {
      isInit.value = false;
      unwatch();
    }
  },
);

onMounted(() => {
  watch(
    targetIsVisible,
    () => {
      if (!finished && !loading.value && targetIsVisible.value) {
        loading.value = true;
        emit('load');
      }
    },
    { immediate: true },
  );
});
</script>

<template>
  <ul class="component-infinite-scroll" :class="{ 'min-h-[calc(100vh_-_48px_-_50px)]': isInit }">
    <slot></slot>
    <li class="flex-x-center color-gray-1" :class="{ 'min-h-[calc(100vh_-_48px_-_50px)]': isInit, 'h-32': !isInit }" ref="target" v-if="!finished">
      <div class="i-svg-spinners-3-dots-scale size-32" v-if="loading"></div>
    </li>
    <div v-else class="bg-#fff py-20 text-center text-12 text-#999aaa font-400 leading-16">{{ $t('mobile.common.nodata') }}</div>
  </ul>
</template>

<style lang="scss" scoped>
</style>
